iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
自我挑戰組

leetcode系列 第 11

leetcode 11. Container With Most Water

  • 分享至 

  • xImage
  •  

題目:
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

給定一個height長度為 的整數數組n。其中繪製了兩條垂直線,使得線n的兩個端點分別為和。ith(i, 0)(i, height[i])

求兩條線,與 x 軸一起形成一個容器,使得容器中裝有最多的水。

返回容器可以儲存的最大水量。

請注意,不要傾斜容器。

題目說明

給一個長度為 n 的整數陣列 height,其中每個元素代表一條直線的高度,座標為 (i, height[i])。任選兩條線與 x 軸構成一個容器,容器能裝水的容量取決於:
https://ithelp.ithome.com.tw/upload/images/20250925/20169340kZtJoQwUcU.png
解題思路

暴力法 (Brute Force)

枚舉所有兩條線,計算容量,取最大值。

時間複雜度 O(n²),會超時。

雙指針法 (最佳解)

用兩個指標 left、right 指向陣列兩端。

計算當前容量 min(height[left], height[right]) * (right - left)。

更新最大值。

移動較矮的那一邊:

因為容量取決於 較矮的一邊,移動較高的一邊不可能增加容量。

不斷縮小區間直到 left >= right。

時間複雜度 O(n)。


上一篇
leetcode 10. Regular Expression Matching
下一篇
leetcode 12. Integer to Roman
系列文
leetcode12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言